/**
 * Created by claim on 16-10-23.
 */
let tables = require('./../../model/index').models;
const helper = require('./../../helper/auth');
const responser = require('./../../lib/responser');

module.exports = router=> {
    router.post('/user/notes/add', async(ctx, next)=> {
        const body = ctx.request.body || {};
        const LoginToken = body.LoginToken || ctx.cookies.get('LoginToken');
        const username = body.username;
        const title = body.title;
        const usernameGotten = await helper.getUsername(LoginToken);
        if (usernameGotten == username) {
            let userId, courseId;
            try {
                userId = (await tables.User.findOne({where: {username: username}})).getDataValue('id');
            } catch (err) {
                responser.catchErr(ctx, "UserId not found", 500);
                return;
            }
            try {
                courseId = (await tables.Course.findOne({where: {title: title}})).getDataValue('id');
                console.log(courseId);
            } catch (e) {
                responser.reject(ctx, "Course do not exist", 404);
                return;
            }
            try {
                tables.Note.create({
                    content: body.content,
                    chapter: body.chapter,
                    UserId: userId,
                    CourseId: courseId
                });
                responser.success(ctx, "success");
            } catch (err) {
                responser.catchErr(ctx, "Create note Failed", 500);
                return;
            }

        } else {
            responser.reject(ctx, "Login expired", 401);
        }
        await next();
    });
    router.get('/user/notes/list', async(ctx, next)=> {
        const username = ctx.query.username;
        const LoginToken = ctx.cookies.get('LoginToken') || ctx.query.LoginToken;
        const usernameGotten = await helper.getUsername(LoginToken);
        if (usernameGotten == username) {
            const title = ctx.query.title;
            const chapter = ctx.query.chapter;
            let userId, courseId;
            try {
                userId = (await tables.User.findOne({where: {username: username}})).getDataValue('id');
            } catch (e) {
                responser.reject(ctx, "UserId not found", 404);
                return;
            }
            try {
                courseId = (await tables.Course.findOne({where: {title: title}})).getDataValue('id');
            } catch (e) {
                responser.reject(ctx, "UserId not found", 404);
                return;
            }
            let notes = await tables.Note.findAll({
                where: {
                    CourseId: courseId,
                    chapter: chapter,
                    UserId: userId
                }
            });
            let results = [];
            notes.forEach(noteInstance=> {
                results.push({
                    updatedAt: noteInstance.getDataValue('updatedAt'),
                    content: noteInstance.getDataValue('content'),
                    id: noteInstance.getDataValue('id')
                });
            });
            responser.success(ctx, {
                result: results
            });


        } else {
            responser.reject(ctx, "Login expired", 401);
        }
        await next();
    });
    router.post('/user/notes/delete', async(ctx, next)=> {
        const username = ctx.query.username;
        const LoginToken = ctx.cookies.get('LoginToken') || ctx.query.LoginToken;
        const usernameGotten = await helper.getUsername(LoginToken);
        if (usernameGotten == username) {
            try {
                const id = ctx.query.id;
                let target = await tables.Note.findOne({
                    where: {id: id}
                });
                target.destroy({force: true});
                responser.success(ctx, "success");
            } catch (e) {
                responser.reject(ctx, "NoteId not found", 404);
            }

        } else {
            responser.reject(ctx, "Login expired", 401);
        }
        await next();
    });
};

